﻿using ZYCommon;
using System;
using System.IO;
using System.Windows.Forms;
using System.Xml;

namespace TextEditor
{
    

    public class A_SaveFile : A_Action
    {
        public override string ActionName()
        {
            return "save";
        }

        public override A_Action Clone()
        {
            A_SaveFile file = new A_SaveFile();
            file.BaseCloneFrom(this);
            return file;
        }
        public override bool Execute()
        {
            base.myOwnerDocument.ToXMLFile(base.myOwnerDocument.Info.FileName);
            base.myOwnerDocument.Modified = false;
            return true;
        }

        public override bool UIExecute()
        {
            string fileName = base.myOwnerDocument.Info.FileName;
            if ((fileName == null) || (fileName.Length == 0))
            {
                using (SaveFileDialog dialog = new SaveFileDialog())
                {
                    dialog.FileName = base.myOwnerDocument.Info.FileName;
                    dialog.CheckFileExists = false;
                    dialog.CheckPathExists = true;
                    dialog.OverwritePrompt = true;
                    dialog.Filter = "XML文件或Base64编码文件|*.xml;*.txt|所有文件|*.*";
                    if (dialog.ShowDialog() == DialogResult.OK)
                    {
                        base.myOwnerDocument.Info.SaveMode = 0;
                        if (dialog.FileName.ToUpper().EndsWith("XML"))
                        {
                            base.myOwnerDocument.ToXMLFile(dialog.FileName);
                        }
                        else
                        {
                            XmlDocument myDoc = new XmlDocument();
                            base.myOwnerDocument.ToXMLDocument(myDoc);
                            string str2 = StringCommon.FormatBase64String(StringCommon.ToBase64String(myDoc.DocumentElement.OuterXml), 8, 2);
                            StreamWriter writer = new StreamWriter(dialog.FileName);
                            writer.Write(str2);
                            writer.Close();
                        }
                        base.myOwnerDocument.Modified = false;
                    }
                }
            }
            else
            {
                base.myOwnerDocument.ToXMLFile(base.myOwnerDocument.Info.FileName);
            }
            return true;
        }
    }
}

